package com.gc.service.impl;

import com.gc.dao.GcTokenDao;
import com.gc.dao.GcUserDao;
import com.gc.pojo.GcToken;
import com.gc.pojo.GcUser;
import com.gc.service.GcAuthCodeService;
import com.gc.service.GcUserService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.UUID;

@Service
public class GcUserServiceImpl implements GcUserService {


    @Autowired
    private GcUserDao gcUserDao;

    @Autowired
    private GcTokenDao gcTokenDao;

    @Reference
    private GcAuthCodeService gcAuthCodeService;


    @Override
    public GcToken register(String email, String password, String code) {
        //注册前校验：
        // 1.是否已注册；
        // 2.用数据库保存的验证码和从邮箱获得的输入验证码进行比对,在10分钟内有效
        if(!isRegistered(email) && gcAuthCodeService.validateAuthCode(email, code) == 0){
            //1.保存注册信息
            GcUser gcUser = new GcUser();
            gcUser.setEmail(email);
            gcUser.setPassword(password);
            gcUser.setCreatetime(new Date());
            gcUser.setLogintime(new Date());
            gcUserDao.save(gcUser);
            //2.注册成功后，根据<用户邮箱+密码>生成token，用UUID模拟
            String tokenText = email + password;
            UUID uuid = UUID.nameUUIDFromBytes(tokenText.getBytes());
            GcToken token = new GcToken();
            token.setEmail(email);
            token.setToken(uuid.toString());
            return gcTokenDao.save(token);
        }
        return  null;
    }

    @Override
    public boolean isRegistered(String email) {
        GcUser gcUser = gcUserDao.findFirstByEmail(email);
        return gcUser != null;
    }

    @Override
    public GcToken login(String email, String password) {
        GcUser gcUser = gcUserDao.findFirstByEmail(email);
        //已注册
        if (gcUser != null && gcUser.getPassword().equalsIgnoreCase(password)) {
            gcUser.setLogintime(new Date());
            gcUserDao.save(gcUser);
            String tokenText = email + password;
            UUID uuid = UUID.nameUUIDFromBytes(tokenText.getBytes());
            GcToken token = new GcToken();
            token.setEmail(email);
            token.setToken(uuid.toString());
            return gcTokenDao.save(token);
        }
        return null;
    }

    @Override
    public String getEmailByToken(String token) {
        GcToken gcToken = gcTokenDao.findFirstByToken(token);
        return token == null ? "NOT FOUND" : gcToken.getEmail();
    }
}
